﻿CREATE TRIGGER [dbo].[trlog_State_Insert]
ON [dbo].[tlog_State]
FOR INSERT
AS

IF @@ROWCOUNT = 0 RETURN

DECLARE @TablePK int,@TableName sysname
SELECT @TablePK = TablePK, @TableName = dbo.clr_RegEx_MatchGroup(TableName,'_(.+)$',0)
FROM inserted WHERE StateTo = 0
IF NOT @TablePK IS NULL BEGIN
	ROLLBACK
	RAISERROR('%s:[%d] mast have Status greater then Zero',16,1,@TableName,@TablePK)
	RETURN
END


IF dbo.Context_IsWorkflowOff() = 0 BEGIN--[

DECLARE @FromID int, @ToID int, @PK int
DECLARE cur CURSOR LOCAL READ_ONLY FOR 
WITH States AS(
SELECT TablePK, StateFrom, StateTo, S.StateFlowPos Pos FROM inserted T INNER JOIN v_State S ON T.StateTo = S.ID
UNION ALL
SELECT States.TablePK,0,ParentID,S.Pos FROM v_State S
INNER JOIN States ON S.ID = States.StateTo
WHERE S.ParentID > 0
)
SELECT TablePK, StateFrom, StateTo FROM States ORDER BY TablePK,Pos

--SELECT TablePK, StateFrom, StateTo FROM inserted

OPEN cur
FETCH NEXT FROM cur INTO @PK, @FromID, @ToID

WHILE @@fetch_status = 0 BEGIN -- 111111111111111111111111111111111
	IF EXISTS(SELECT * FROM fs_NextStates(@FromID) WHERE StateToID = @ToID)
		 OR 
		 ISNULL(@FromID,0) = 0
		EXEC state__Action @PK,@FromID,@ToID
	ELSE BEGIN -- 222222222222222222222222222222222

		DECLARE @Group sysname SET @Group = dbo.UserGroups_TEXT()
		DECLARE @SF sysname, @ST sysname

		SELECT  @SF = '[' + dbo.fs_TableName(SF.TableName) + N'].[' + SF.Name + ']',
						@ST = '[' + dbo.fs_TableName(ST.TableName) + N'].[' + ST.Name + ']'
		FROM inserted i	INNER JOIN t_State SF ON i.StateFrom = SF.ID 
										INNER JOIN t_State ST ON i.StateTo = ST.ID

		RAISERROR('Group %s does not have permition to send from %s to %s',16,1,@Group,@SF,@ST)

		ROLLBACK TRAN BREAK
	END -- 22222222222222222222222222222222

	FETCH NEXT FROM cur INTO @PK, @FromID, @ToID
END -- 11111111111111111111111111111111

CLOSE cur DEALLOCATE cur

END--]

UPDATE tlog_State WITH(UPDLOCK) SET TableName = t_State.TableName
FROM t_State
INNER JOIN tlog_State ON t_State.ID = tlog_State.StateTo
INNER JOIN inserted ON inserted.ID = tlog_State.ID


UPDATE dbo.tlog_State WITH(UPDLOCK) SET IsLast = 0
FROM tlog_State
INNER JOIN
(SELECT i.TablePK,tl.TableName,i.ID FROM /*tlog_State*/inserted i INNER JOIN tlog_State tl WITH(NOLOCK) ON i.ID = tl.ID) i
	ON tlog_State.TableName = i.TableName AND
		 tlog_State.TablePK = i.TablePK AND
		 tlog_State.ID <> i.ID

IF @@ROWCOUNT = 0
	UPDATE tlog_State WITH(UPDLOCK) SET IsFirst = 1,IsLast = 1
	FROM tlog_State INNER JOIN /*tlog_State AS*/ inserted ON tlog_State.ID = inserted.ID
